<template>
  <div>
    <el-form :inline="true">
      <el-form-item prop="province">
        <el-form-item>
          <v-distpicker @selected="onSearchSelected" :provinceOut="searchStaff.provinceCode" only-province>
          </v-distpicker>
        </el-form-item>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model.trim="searchStaff.name" placeholder="员工名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchStaff.departmentId" clearable placeholder="请选择部门">
          <el-option
            v-for="item in allDepartment"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchStaff.positionId" clearable placeholder="请选择岗位">
          <el-option
            v-for="item in allPosition"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-dropdown @command="handleCommand">
          <el-button type="primary">导入<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <a href="/static/员工导入模板.xlsx"
               download="员工导入模板.xlsx"
               style="color:#5a5e66;text-decoration: none "><el-dropdown-item command="handleDownload">模板下载
            </el-dropdown-item></a>
            <el-dropdown-item command="handleImport">数据导入</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="excelExport">数据导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 员工一览 -->
    <custom-table
      :columns="columns"
      :data="staffList"
      :tableLoadingFlag="tableLoadingFlag"
      :operationColumn="operationColumn"
      :pagination="pagination">
    </custom-table>

    <!-- 员工模板导入模态框 -->
    <el-dialog title="模板导入" :visible.sync="uploadVisible"
               :close-on-click-modal="false" :before-close="uploadCancel">
      <div>
        <el-form label-width="80px" ref="uploadForm" :inline="true">
          <el-form-item style="padding-left: 120px">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="myHeaders"
              name="file"
              :on-error="uploadError"
              :on-success="uploadSuccess"
              :before-upload="beforeAvatarUpload"
              multiple
              drag
              :limit="1"
              :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em><br/>只能上传xlsx文件，且不超过10M</div>
            </el-upload>
          </el-form-item>
          <!--显示导入中错误的数据-->
          <div style="height: 200px;overflow-y: auto" v-if="hideTable">
            <custom-table
              :data="wrongDataList"
              :columns="detailColumns">
            </custom-table>
          </div>
        </el-form>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="uploadCancel()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 员工新增，修改模态框 -->
    <el-dialog :title="dialogType ==='add'? '新增员工':'修改员工信息'" :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :model="staffDto" :rules="staffRules" label-width="90px" ref="staffForm">
        <el-form-item label="员工编号" prop="code">
          <el-input v-model="staffDto.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="staffDto.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="staffDto.tel" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="staffDto.departmentId" placeholder="请选择部门">
            <el-option
              v-for="item in departmentOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="岗位" prop="positionId">
          <el-select v-model="staffDto.positionId" placeholder="请选择部门岗位">
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区">
          <el-row>
            <el-col :span="9" prop="provinceRule">
              <el-select v-model="staffDto.provinceCode" clearable placeholder="请选择省份" @change="getCity()">
                <el-option
                  v-for="item in allProvince"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="9" prop="cityRule">
              <el-select v-model="staffDto.cityCode" clearable placeholder="请选择城市">
                <el-option
                  v-for="item in allCityInfo"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="staffDto.address" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CustomTable from '@/components/table/CustomTable'
  import {baseInfo} from '@/utils/fetch'
  import Distpicker from '@/components/distpicker/index'
  import {apiGetStaffList, apiGetStaffById, apiDelStaff, apiAddStaff, apiUpdStaff, apiExport} from '@/api/basic/info/inside/staff'
  import {apiStaffReadExcel} from '@/api/excel/excelRead'
  import store from '@/store'
  import {apiGetDepartmentList, apiGetPositionList, apiGetCity} from '@/api/dictionary'
  import {downloadExcel} from "../../../../utils";

  export default {
    name: 'staff',
    components: {CustomTable, Distpicker},
    created() {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      this.getAllProvince()
      this.getStaffList(listQuery)
      this.getAllDepartment()
      this.getAllPosition()
    },
    data() {
      return {
        uploadUrl: baseInfo() + '/api/v1/upload',
        myHeaders: {'access_token': store.getters.token},
        // 上传文件显示
        fileList: [],
        // 文件上传路径
        importFileUrl: baseInfo() + '/api/v1/upload',
        // 文件上传参数
        upLoadData: {},
        dialogVisible: false,                     // 模态框相关数据
        dialogType: '',
        uploadVisible: false,
        hideTable: false,
        departmentOptions: this.getDepartmentList(),
        positionOptions: this.getPositionList(),
        filePath: '',
        // 所有省份
        allProvince: [],
        // 所有城市
        allCityInfo: [],
        allDepartment: [],
        allPosition: [],
        searchStaff: {
          provinceCode: '',
          positionId: '',
          name: '',
          departmentId: ''
        },
        listQuery: {
          provinceCode: undefined,
          positionId: undefined,
          name: undefined,
          departmentId: undefined
        },
        staffDto: {
          code: '',
          name: '',
          tel: '',
          departmentId: undefined,
          positionId: undefined,
          provinceCode: '',
          cityCode: '',
          province: '',
          city: '',
          address: ''
        },
        staffRules: {
          code: [
            {required: true, message: '请输入员工编号', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入员工姓名', trigger: 'blur'},
            {max: 20, message: '长度不得超过20字符', trigger: 'blur'}
          ],
          tel: [
            {required: true, message: '请输入员工联系电话', trigger: 'blur'}
          ],
          departmentId: [
            {type: 'number', required: true, message: '请选择员工部门', trigger: 'change'}
          ],
          positionId: [
            {type: 'number', required: true, message: '请选择员工部门岗位', trigger: 'change'}
          ],
          address: [
            {required: true, message: '请输入详细地址', trigger: 'blur'},
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ],
          cityRule: [
            {required: true, message: '请选择城市', trigger: 'change'}
          ],
          provinceRule: [
            {required: true, message: '请选择省份', trigger: 'change'}
          ]
        },
        tableLoadingFlag: false,             // 员工一览相关数据
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '员工编号', name: 'code', align: 'center'},
          {label: '员工姓名', name: 'name', align: 'center'},
          {label: '省份', name: 'province', align: 'center'},
          {label: '部门', name: 'department', align: 'center'},
          {label: '岗位', name: 'position', align: 'center'}
        ],
        detailColumns: [
          {label: '错误行号', name: 'wrongRowNO', width: '77', height: '40', align: 'center'},
          {label: '错误原因', name: 'reason', width: '120', height: '40', align: 'center'},
          {label: '员工编号', name: 'code', width: '80', height: '40', align: 'center'},
          {label: '员工姓名', name: 'name', width: '80', height: '40', align: 'center'},
          {label: '联系方式', name: 'tel', width: '80', height: '40', align: 'center'},
          {label: '部门', name: 'department', width: '80', height: '40', align: 'center'},
          {label: '岗位', name: 'position', width: '80', height: '40', align: 'center'},
          {label: '省份', name: 'province', width: '80', height: '40', align: 'center'},
          {label: '城市', name: 'city', width: '80', height: '40', align: 'center'},
          {label: '详细地址', name: 'address', width: '80', height: '40', align: 'center'}
        ],
        operationColumn: {
          width: '100',
          operations: [
            {name: '编辑', callback: this.handleEdit},
            {name: '删除', callback: this.handleDel}
          ]
        },
        staffList: [],
        wrongDataList: [],
        pagination: this.getData(this.getStaffList)
      }
    },
    methods: {
      handleCommand(command) {
        if (command === 'handleImport') {
          this.dialogType = 'upload'
          this.uploadVisible = true
        } else if (command === 'handleDownload') {
        }
      },
      uploadCancel () {
        this.uploadVisible = false
        this.wrongDataList = []
        this.fileList = []
        this.hideTable = false
        this.$refs['uploadForm'].resetFields()
      },
      excelExport() {
        let paramsPost = {
          name: this.searchStaff.name,
          department: this.searchStaff.departmentId,
          position: this.searchStaff.positionId,
          provinceCode: this.searchStaff.provinceCode
        }
        apiExport(paramsPost).then(response => {
          downloadExcel(response.data, '自有售后员工信息导出表')
        }).catch(() => {
          console.log('error')
        })
      },
      uploadSuccess(response, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传文件成功！'
        })
        let filePath = response.data
        this.excelRead(filePath)
      },
      // 上传错误
      uploadError(err, file, fileList) {
        this.$message({
          showClose: true,
          message: '上传失败，请重试！'
        })
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload(file) {
        const extension = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension) {
          this.$message({
            showClose: true,
            message: '上传模板只能是 xlsx 格式!'
          })
        }
        if (!isLt2M) {
          this.$message({
            showClose: true,
            message: '上传模板大小不能超过 10MB!'
          })
        }

        return extension && isLt2M
      },
      excelRead(filePath) {
        apiStaffReadExcel(filePath).then(response => {
          if (response.data) {
            this.wrongDataList = response.data
            this.hideTable = true
          } else {
            this.$message({
              showClose: true,
              message: '导入执行中，请稍后',
              type: 'success'
            })
            this.hideTable = false
            this.getStaffList({
              pageNumber: this.pagination.currentPage,
              pageSize: this.pagination.pageSize
            })
          }
          this.fileList = []
        })
      },
      getAllProvince () {
        apiGetCity().then(response => {
          this.allProvince = response.data
        })
      },
      getCity() {
        this.staffDto.cityCode = ''
        if (this.staffDto.provinceCode === '') {
          this.allCityInfo = []
        }
        let listQuery = {
          province: this.staffDto.provinceCode
        }
        apiGetCity(listQuery).then(response => {
          this.allCityInfo = response.data
        })
      },
      getStaffList(listQuery) {
        this.tableLoadingFlag = true
        if (listQuery.provinceCode === undefined) {
          listQuery.provinceCode = this.searchStaff.provinceCode
        }
        if (listQuery.positionId === undefined) {
          listQuery.positionId = this.searchStaff.positionId
        }
        if (listQuery.name === undefined) {
          listQuery.name = this.searchStaff.name
        }
        if (listQuery.departmentId === undefined) {
          listQuery.departmentId = this.searchStaff.departmentId
        }
        apiGetStaffList(listQuery).then(response => {
          this.staffList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      onSearchSelected(data) {             // 省市区联动回调
        this.searchStaff.provinceCode = data.province.code
      },
      getAllDepartment() {
        apiGetDepartmentList().then(response => {
          this.allDepartment = response.data
        })
      },
      getAllPosition() {
        apiGetPositionList().then(response => {
          this.allPosition = response.data
        })
      },
      handleAdd() {
        this.dialogType = 'add'
        this.dialogVisible = true
        this.staffDto = {
          code: '',
          name: '',
          tel: '',
          departmentId: undefined,
          positionId: undefined,
          provinceCode: '',
          cityCode: '',
          province: '',
          city: '',
          address: ''
        }
        if (this.$refs['staffForm']) {
          this.$refs['staffForm'].resetFields()
        }
      },
      handleEdit(row) {
        apiGetStaffById(row.id).then(response => {
          this.staffDto.provinceCode = response.data.provinceCode
          this.getCity()
          this.staffDto = response.data
          this.dialogType = 'edit'
          this.dialogVisible = true
        })
      },
      handleDel(row) {
        this.$confirm('确定删除该员工?', '删除员工', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          apiDelStaff(row.id).then(() => {
            this.$message({
              showClose: true,
              type: 'success',
              message: '删除成功!'
            })
            this.getStaffList(this.listQuery)
          })
        }).catch(() => {
        })
      },
      submit() {
        this.$refs.staffForm.validate((valid) => {
          if (valid) {
            if (this.dialogType === 'add') {
              this.addSubmit()
            } else {
              this.updSubmit()
            }
          } else {
            return false
          }
        })
      },
      addSubmit() {
        apiAddStaff(this.staffDto).then(() => {
          this.$message({
            showClose: true,
            message: '新增成功',
            type: 'success'
          })
          this.cancel()
          this.getStaffList(this.listQuery)
        })
      },
      updSubmit() {
        apiUpdStaff(this.staffDto).then(() => {
          this.$message({
            showClose: true,
            message: '更新成功',
            type: 'success'
          })
          this.cancel()
          this.getStaffList(this.listQuery)
        })
      },
      cancel() {
        this.dialogVisible = false
        this.$refs['staffForm'].resetFields()
      },
      searchData() {
        this.listQuery.provinceCode = this.searchStaff.provinceCode
        this.listQuery.positionId = this.searchStaff.positionId
        this.listQuery.name = this.searchStaff.name
        this.listQuery.departmentId = this.searchStaff.departmentId
        this.pagination.currentPage = 1
        this.pagination.pageSize = 10
        this.getStaffList(this.listQuery)
      }
    }
  }
</script>
